/**
 * Created by zhourh on 2018/6/14.
 * 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

 示例：

 输入：1->2->4, 1->3->4
 输出：1->1->2->3->4->4

 链表
 *
 */
public class MergeTwoSortedLists {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        node1.next = new ListNode(2);
        node1.next.next = new ListNode(4);

        ListNode node2 = new ListNode(1);
        node2.next = new ListNode(3);
        node2.next.next = new ListNode(4);

        ListNode result = new MergeTwoSortedLists().mergeTwoLists(node1, node2);

        while (result != null) {
            System.out.print(result.val + "->");
            result = result.next;
        }
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null && l2 == null) {
            return null;
        }

        if (l1 != null && l2 == null) {
            return l1;
        }

        if (l1 == null && l2 != null) {
            return l2;
        }

        ListNode nodeHeadMerged = null;
        ListNode nodeTailMerged = null;

        if (l1.val <= l2.val) {
            nodeHeadMerged = l1;
            l1 = l1.next;
        } else {
            nodeHeadMerged = l2;
            l2 = l2.next;
        }

        nodeTailMerged = nodeHeadMerged;

        while (l1 != null || l2 != null) {
            if (l1 == null) {
                nodeTailMerged.next = l2;
                break;
            }

            if (l2 == null) {
                nodeTailMerged.next = l1;
                break;
            }

            if (l1.val <= l2.val) {
                nodeTailMerged.next = l1;
                nodeTailMerged = l1;
                l1 = l1.next;
                continue;
            }

            nodeTailMerged.next = l2;
            nodeTailMerged = l2;
            l2 = l2.next;
        }

        return nodeHeadMerged;
    }
}
